package com.qianfeng.android.baoman;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.qianfeng.android.baoman.model.LoginUser;
import com.qianfeng.android.baoman.task.LoginTask;
import com.qianfeng.android.baoman.task.TaskInterface;
import com.qianfeng.android.baoman.util.HttpTool;
import com.qianfeng.android.baoman.util.LoginHelper;

import org.json.JSONObject;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.line.Line;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.tencent.weibo.TencentWeibo;


public class LoginActivity extends BaseActivity implements Handler.Callback, PlatformActionListener, TaskInterface {

    private EditText loginUser;
    private EditText loginPass;

    private LinearLayout loadLayout;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        setActionBarTitle("登陆暴走");
        setBackVisible(true);
        setFunctionVisible(true);
        ImageButton fun = (ImageButton) findViewById(R.id.action_function);
        fun.setImageResource(R.drawable.regist_btn_selector);
        fun.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        loadLayout = (LinearLayout) findViewById(R.id.load_layout);
        loginUser = (EditText) findViewById(R.id.activity_login_userName);
        loginPass = (EditText) findViewById(R.id.activity_login_password);
        ImageButton imageButton = (ImageButton) findViewById(R.id.activity_login_btn);
        imageButton.setOnClickListener(this);

        ImageButton loginQQ = (ImageButton) findViewById(R.id.activity_login_qq);
        loginQQ.setOnClickListener(this);

        ImageButton sinaBtn = (ImageButton) findViewById(R.id.activity_login_sina);
        sinaBtn.setOnClickListener(this);
        ImageButton weibo = (ImageButton) findViewById(R.id.activity_login_qq_weibo);
        weibo.setOnClickListener(this);


    }

    private void initLogin() {
        loadLayout.setVisibility(View.VISIBLE);
        String userName = loginUser.getText().toString();
        String userPass = loginPass.getText().toString();
        if (userName != null) {
            if (userPass != null) {
                if (userPass.length() >= 6) {
                    LoginTask task = new LoginTask(this);
                    task.execute(userName, userPass);
                } else {
                    Toast.makeText(this, "用户名密码不能小于六位", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(this, "用户名密码不能为空", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "用户名不能为空", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void onClick(View v) {

        int id = v.getId();
        switch (id) {
            case R.id.action_function:
                Intent intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.activity_login_btn:
//                LoginHelper.login_v2("731436452@qq.com", "1234567987");
                initLogin();

                break;
            case R.id.activity_login_sina:
                ShareSDK.initSDK(this);
                authorize(new SinaWeibo(this));
                break;
            case R.id.activity_login_qq_weibo:
                ShareSDK.initSDK(this);
                authorize(new TencentWeibo(this));
                break;
            case R.id.activity_login_qq:
                ShareSDK.initSDK(this);
                authorize(new QQ(this));
                break;
            default:
                super.onClick(v);
                break;
        }
    }

    //TODO 第三方登陆
    public void getUserInfo() {
        ShareSDK.initSDK(this);
        //TODO 1 获取哪一个平台的用户
        authorize(new QQ(this));
        //TODO 2 。把获取的用户信息传递给服务器
    }


    private void authorize(Platform plat) {
        if (plat == null) {
            //如果没有指定平台，现在强制选择新浪微博
            plat = new SinaWeibo(this);
//            popupOthers();
//            return;
        }
        //判断指定平台是否已经完成授权
        //没有授权的时候进行授权的操作，最终会执行showUser（）这个方法
        //
        if (plat.isValid()) {
            PlatformDb db = plat.getDb();
            String userId = db.getUserId();
            String userName = db.getUserName();
            String token = db.getToken();
            String platformNname = db.getPlatformNname();
            String userIcon = db.getUserIcon();

            if (userId != null) {
                //用于发送注册、登陆 成功过的消息
                Message message = new Message();
                Bundle data = new Bundle();
                data.putString("userName", userName);
                data.putString("userId", userId);
                data.putString("token", token);
                data.putString("platformNname", platformNname);
                message.setData(data);
                UIHandler.sendMessage(message, this);
//                UIHandler.sendEmptyMessage(1, this);
                Log.d("LoginActivity", plat.getName());
                Log.d("LoginActivity", userId + "");
//                login(plat.getName(), userId, null);
                String str2 = "http://api.ibaozou.com/users/verify_bind.app?client_id=10230158&uid="
                        + userId + "&oauth_client_name=qq_connect";
                System.out.println("str2 = " + str2);
                String str3 = "http://api.ibaozou.com/users/verify_bind.app?client_id=10230158&uid="
                        + token + "&oauth_client_name=qq_connect";
                return;
            }
        }
        //用于检测用户在登陆的时候操作的状态
        //当用户授权成功，会进行回调，回调内会传递一些用户的信息
        plat.setPlatformActionListener(this);
        // true不使用SSO授权，false使用SSO授权
        plat.SSOSetting(true);
        //获取用户资料
        plat.showUser(null);
    }

    /**
     * 如果用户信息渠道了，那么会发送消息到这个方法。
     *
     * @param msg
     * @return
     */
    @Override
    public boolean handleMessage(Message msg) {
        Bundle data = msg.getData();
        String userName = data.getString("userName");
        String userId = data.getString("userId");
        String token = data.getString("token");
        String platformNname = data.getString("platformNname");
        System.out.println("platformNname = " + platformNname);
        String str = "http://api.ibaozou.com/users/verify_bind.app?client_id=10230158&uid="
                + userName + "&oauth_client_name=qq_connect";
        System.out.println("str = " + str);
        String str2 = "http://api.ibaozou.com/users/verify_bind.app?client_id=10230158&uid="
                + userId + "&oauth_client_name=qq_connect";
        System.out.println("str2 = " + str2);
        String str3 = "http://api.ibaozou.com/users/verify_bind.app?client_id=10230158&uid="
                + token + "&oauth_client_name=qq_connect";
        System.out.println("str3 = " + str3);

        return false;
    }
/////////////////////////////////授权认证的时候回调的方法///////////////////////////////////////////////////////

    /**
     * 授权成功，可以获取用户信息
     *
     * @param platform
     * @param i
     * @param stringObjectHashMap
     */
    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> stringObjectHashMap) {
        //获取哪一个平台的授权登陆信息
        String name = platform.getName();
        PlatformDb db = platform.getDb();

        String token = db.getToken();
        //授权的用户名称
        String userName = db.getUserName();
        String userId = db.getUserId();

        Log.i("Login", "userName:" + userName + ":" + token);
    }

    /**
     * 授权出错
     *
     * @param platform
     * @param i
     * @param throwable
     */
    @Override
    public void onError(Platform platform, int i, Throwable throwable) {
        Toast.makeText(this, "認證失敗", Toast.LENGTH_SHORT).show();
    }

    /**
     * 用户取消了授权
     *
     * @param platform
     * @param i
     */
    @Override
    public void onCancel(Platform platform, int i) {

    }


    //登陆后返回的数据
    @Override
    public void backResult(JSONObject jsonObject) {
        loadLayout.setVisibility(View.GONE);
        if (jsonObject != null) {
            LoginUser loginUser = new LoginUser();
            loginUser.parseJSON(jsonObject);
            Constants instance = Constants.getInstance();
            instance.save("access_token", loginUser.getAccess_token());
            instance.save("user_avatar", loginUser.getUser_avatar());
            instance.save("user_name", loginUser.getUser_name());
            instance.save("client_id", loginUser.getClient_id());
            instance.save("user_id", Integer.toString(loginUser.getUser_id()));

            instance.save("lastTime", Long.toString(System.currentTimeMillis()));
//            LoginHelper.bindUserToken(loginUser.getUser_id()+"","",loginUser.getAccess_token());

            Intent intent = new Intent();
            intent.putExtra("loginUser", loginUser);
            setResult(23, intent);
            finish();
        } else {
            Toast.makeText(this, "网络请求失败", Toast.LENGTH_SHORT);
        }
    }


}



